<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>

<body>
  <h1>拦截器练习</h1>
  <button id="btn">点击请求数据</button>
  <script>
    // 创建axios实例
    const myAxios = axios.create({
      baseURL: '/',
      timeout: 1000,
      headers: {}
    })

    // 设置请求拦截器
    myAxios.interceptors.request.use(config => {
      const token = 'aishdjasdaskdkdsasdads..'
      // 让请求头携带token
      config.headers.token = token
      // 返回config
      return config
    }, (error) => {
      return Promise.reject(error.message)
    })

    // 设置响应拦截器
    myAxios.interceptors.response.use(response => {
      // 只拿正确的信息,错误的信息交给异常处理
      if (response.data.code !== 10000) {
        return Promise.reject(response.data.msg)
      }
      return response.data.data
    }, (error) => {
      return Promise.reject(error.message)
    })

    // 获取元素
    const obtn = document.getElementById('btn')

    obtn.onclick = async function () {
      try {
        const re = await myAxios.get('/userInfo', {
          params: {
            userId: '001'
          }
        })
        console.log(re)
      } catch (e) {
        console.log(e)
      }
    }
  </script>
</body>

</html>